package com.sample.rx;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.loyal.client.RxConfig;
import com.loyal.client.impl.RxSubscriberListener;
import com.loyal.rx.RxPermission;
import com.loyal.rx.RxUtil;
import com.sample.rx.libs.rxjava.RxProgressSubscriber;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;

public class MainActivity extends AppCompatActivity implements RxSubscriberListener<String>,
        View.OnClickListener, RxPermission.SingleCallback, RxPermission.MultipleCallback {
    private SimpleDateFormat formatter = new SimpleDateFormat("mm:ss", Locale.getDefault());

    private static final int WHAT_LOGIN = 2;
    private static final int WHAT_TIMEOUT1 = 4;
    private static final int WHAT_TIMEOUT2 = 6;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.login).setOnClickListener(this);
        findViewById(R.id.rx_timeout1).setOnClickListener(this);
        findViewById(R.id.rx_timeout2).setOnClickListener(this);
        findViewById(R.id.rx_download).setOnClickListener(this);
        findViewById(R.id.rx_single).setOnClickListener(this);
        findViewById(R.id.rx_multi).setOnClickListener(this);
        permission();
    }

    private void permission() {
        startActivity(new Intent(this, TestActivity.class));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login:/*注意*/
                login();
                break;
            case R.id.rx_timeout1:
                rxTimeOut1();
                break;
            case R.id.rx_timeout2:
                rxTimeOut2();
                break;
            case R.id.rx_download:
                download();
                break;
            case R.id.rx_single:
                permission();
                //
                /*RxPermission.getInstance().with(this).single(this,
                        Manifest.permission.READ_PHONE_STATE);*/
                break;
            case R.id.rx_multi:
                permission();

                /*RxPermission.getInstance().with(this).multiple(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.READ_PHONE_STATE);*/
                break;
        }
    }

    private void login() {
        Log.e("login: ", "登录");
        RxConfig builder = RxConfig.getInstance();
        builder.setHttpOrHttps("https");
        builder.setUrl("192.168.0.107");
        builder.setPort("9081");
        builder.setNameSpace("mwm");
        long current = System.currentTimeMillis();
        Log.e("mwm: ", builder.toString());

        RxProgressSubscriber<String> subscriber = new RxProgressSubscriber<>(this, builder);
        subscriber.setDialogMessage("loading...").showProgressDialog(true);
        subscriber.setTag(current);
        subscriber.setWhat(WHAT_LOGIN).setSubscribeListener(this);
        Map<String, String> map = new HashMap<>();
        map.put("account", "loyal");
        map.put("password", "loyal");
        RxUtil.rxExecute(subscriber.doLogin(new Gson().toJson(map)), subscriber);
    }

    private void rxTimeOut1() {
        Log.e("rxTimeOut1: ", "超时测试1");
        RxConfig builder = RxConfig.getInstance();
        builder.setHttpOrHttps("https");
        builder.setUrl("192.168.0.107");
        builder.setPort("9080");
        builder.setNameSpace("pospay");
        Log.e("TAG", builder.toString());
        OkHttpClient.Builder ctBuilder = new OkHttpClient.Builder();
        ctBuilder.readTimeout(12L, TimeUnit.SECONDS);//设置读取超时
        ctBuilder.writeTimeout(12L, TimeUnit.SECONDS);//设置写入超时
        ctBuilder.connectTimeout(12L, TimeUnit.SECONDS);//设置连接超时
        builder.setOkCtBuilder(ctBuilder);
        long current = System.currentTimeMillis();
        RxProgressSubscriber<String> subscriber = new RxProgressSubscriber<>(this, builder);
        subscriber.setDialogMessage("loading...").showProgressDialog(true);
        subscriber.setTag(current);
        subscriber.setWhat(WHAT_TIMEOUT1).setSubscribeListener(this);
        Map<String, String> map = new HashMap<>();
        map.put("account", "loyal");
        map.put("password", "loyal");
        RxUtil.rxExecute(subscriber.doLogin(new Gson().toJson(map)), subscriber);
    }

    private void rxTimeOut2() {
        Log.e("rxTimeOut2: ", "超时测试2");
        RxConfig builder = new RxConfig();
        builder.setHttpOrHttps("https");
        builder.setUrl("192.168.0.155");
        builder.setNameSpace("jtwf_self");
        OkHttpClient.Builder ctBuilder = new OkHttpClient.Builder();
        ctBuilder.readTimeout(10L, TimeUnit.SECONDS);//设置读取超时
        ctBuilder.writeTimeout(10L, TimeUnit.SECONDS);//设置写入超时
        ctBuilder.connectTimeout(10L, TimeUnit.SECONDS);//设置连接超时
        builder.setOkCtBuilder(ctBuilder);

        long current = System.currentTimeMillis();

        Log.e("jtwf_self: ", builder.toString());

        RxProgressSubscriber<String> subscriber = new RxProgressSubscriber<>(this, builder);
        subscriber.setDialogMessage("loading...").showProgressDialog(true);
        subscriber.setTag(current);
        subscriber.setWhat(WHAT_TIMEOUT2).setSubscribeListener(this);
        Map<String, String> map = new HashMap<>();
        map.put("account", "loyal");
        map.put("password", "loyal");
        RxUtil.rxExecute(subscriber.doLogin(new Gson().toJson(map)), subscriber);
    }

    private void download() {
        Log.e("download: ", "开始下载");
        RxProgressSubscriber<ResponseBody> subscriber = new RxProgressSubscriber<>(this);
        String url = "http://192.168.0.110:8080/mwm/action.do?method=doShowIconByIO&account=loyal";
        subscriber.setSubscribeListener(new RxSubscriberListener<ResponseBody>() {

            @Override
            public void onResult(int what, Object tag, ResponseBody responseBody) {
                try {
                    Log.e("onResult: ", "");
                    //File iconFile = new File(FileUtil.imagePath, "icon_" + tag + ".jpg");
                    //FileUtil.deleteFile(iconFile);
                    //String save = ImageUtil.saveToFile(iconFile, responseBody.byteStream());
                    //OutUtil.println(TextUtils.isEmpty(save) ? "下载失败" : "保存成功");
                } catch (Exception e) {
                    //OutUtil.println("imageService::Error--" + e);
                    onError(what, tag, e);
                }
            }

            @Override
            public void onError(int what, Object tag, Throwable e) {
                Log.e("onError: ", "", e);
            }
        });
        RxUtil.rxExecuteAndCompute(subscriber.downloadImage(url), subscriber);
    }

    @Override
    public void onResult(int what, Object tag, String result) {
        long current = System.currentTimeMillis();
        long last = (long) tag;
        String time = formatter.format(new Date(current - last));
        Log.e("start->", "" + time);
        switch (what) {
            case WHAT_LOGIN:
                //
                Log.e("onResult", "endTime->" + time);
                break;
            case WHAT_TIMEOUT1:
                Log.e("onResult", "1endTime->" + time);
                break;
            case WHAT_TIMEOUT2:
                Log.e("onResult", "2endTime->" + time);
                break;
        }
    }

    @Override
    public void onError(int what, Object tag, Throwable e) {
        long current = System.currentTimeMillis();
        long last = (long) tag;
        String time = formatter.format(new Date(current - last));
        switch (what) {
            case WHAT_LOGIN:
                Log.e("onError", "login-endTime->" + time);
                //Log.e("onError", "LOGIN", e);
                break;
            case WHAT_TIMEOUT1:
                Log.e("onError", "1endTime->" + time);
                //Log.e("onError", "TIMEOUT", e);
                break;
            case WHAT_TIMEOUT2:
                Log.e("onError", "2endTime->" + time);
                //Log.e("onError", "rxJava", e);
                break;
        }
    }

    @Override
    public void onSingleCallback(int code, boolean successful, Throwable e) {
        Log.e("onSingleCallback: ", "" + successful);
    }

    @Override
    public void onMultipleCallback(@NonNull List<String> refuseList,
                                   @NonNull List<String> rationaleList,
                                   @Nullable Throwable e) {
        Log.e("onMultipleCallback: ", "-本次被拒绝->" + refuseList);
        Log.e("onMultipleCallback: ", "-以后不再询问->" + rationaleList);
    }
}